#include "buffer/buffer.h"
#include "test.h"

TEST_CASE("Buffer: initialize,writeableBytes,readableBytes", "[buffer]")
{
    std::string s1;
    LOG_INFO("s1 capcity: {}", s1.capacity());
    s1.reserve(1024);
    LOG_INFO("after reserve, s1 capcity: {}", s1.capacity());

    using namespace zh;
    Buffer buffer1;
    LOG_INFO("buffer1 writeableBytes before initialize: {}", buffer1.writeableBytes());
    buffer1.initialize();
    REQUIRE(buffer1.writeableBytes() == 1024);
    REQUIRE(buffer1.readableBytes() == 0);
}

TEST_CASE("Buffer: append,toString,updateReadPtr,length", "[buffer]")
{
    using namespace zh;
    Buffer buffer1;
    buffer1.append("hello buffer");
    REQUIRE(buffer1.toString() == "hello buffer");
    std::string s1 = "1024";
    buffer1.append(s1);
    REQUIRE(buffer1.toString() == "hello buffer1024");
    buffer1.updateReadPtr(6);
    REQUIRE(buffer1.toString() == "buffer1024");
    buffer1.updateReadPtr(20);
    REQUIRE(buffer1.length() == 0);
}

TEST_CASE("Buffer: readFD", "[buffer]")
{
    using namespace zh;
    int FD = open("./logs/log.txt", O_RDONLY);
    if (FD == -1)
    {
        LOG_ERROR("open file error");
    }
    else
    {
        Buffer buffer1;
        int    saveErrorNo;
        buffer1.readFD(FD, &saveErrorNo);
        LOG_INFO("after readFD, readableBytes: {}", buffer1.readableBytes());
        REQUIRE(buffer1.readableBytes() > 0);
    }

    close(FD);
}

TEST_CASE("Buffer: writeFD", "[buffer]")
{
    using namespace zh;
    int FD = open("./logs/test.txt", O_CREAT | O_TRUNC | O_WRONLY);
    if (FD == -1)
    {
        LOG_ERROR("open file error");
    }
    else
    {
        Buffer buffer1;
        buffer1.append("hello buffer write fd\n");
        REQUIRE(buffer1.readableBytes() > 0);
        int saveErroNo;
        buffer1.writeFD(FD, &saveErroNo);
        REQUIRE(buffer1.readableBytes() == 0);
    }
    close(FD);
}